package com.lyf.core.util;

import java.util.Map;
import java.util.Map.Entry;

import org.apache.shiro.config.Ini;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.config.IniFilterChainResolverFactory;
import org.springframework.util.CollectionUtils;

import com.lyf.core.compant.Perm;

public class ShiroPermissionFactory extends ShiroFilterFactoryBean{

	/**配置中的过滤链*/  
    public static String definitions;  
      
    /**权限service*/  
//    @Autowired  
//    private RoleService roleService;  
  
    /** 
     * 从数据库动态读取权限 
     */  
    @Override  
    public void setFilterChainDefinitions(String definitions) {  
        ShiroPermissionFactory.definitions = definitions;  
          
 
        //数据库动态权限  
        //字符串拼接权限  
        Map<String, Perm> ms = CommonUtils.getAllUrlPerms();
        for(Entry<String, Perm> e: ms.entrySet()) {
        	String url = e.getKey();
        	if(url == null ||url.trim().equals("")) continue;
        	if(url.startsWith("./")){
        		url = url.substring(1);
        	}
        	
        	definitions = definitions + url + " = "+"perms["+ url +"] \n";  
        }
 
        
        System.out.println("definitions : " + definitions);
        
        //从配置文件加载权限配置  
        Ini ini = new Ini();  
        ini.load(definitions);  
        Ini.Section section = ini.getSection(IniFilterChainResolverFactory.URLS);  
        if (CollectionUtils.isEmpty(section)) {  
            section = ini.getSection(Ini.DEFAULT_SECTION_NAME);  
        }  
          
        //加入权限集合  
        setFilterChainDefinitionMap(section);  
    }  
}  